package com.example.demo.service;

import com.alibaba.fastjson.JSON;
import com.example.demo.pojo.Content;
import com.example.demo.utils.HtmlParseUtil;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchAction;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.*;
import javax.xml.transform.Source;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lee
 * @date 2021年06月14日 19:29
 */
@Service
public class ContentService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    HtmlParseUtil htmlParseUtil;

    //1、解析数据放入es 索引中
    public Boolean parseContent(String keyword) throws Exception {

       //List<Content> contents = htmlParseUtil.parseJd(keyword);


        ArrayList<Content> contents = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            contents.addAll(htmlParseUtil.parseJdByPage(keyword, i, 30));
        }


        //把查询出来的数据放入es中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout(TimeValue.timeValueSeconds(2L));
        for (int i = 0; i < contents.size(); i++) {
           // if (false == iSExistData("jd-goods", contents.get(i).getTitle())){
                bulkRequest.add(
                        new IndexRequest("jd-goods")
                                .source(JSON.toJSONString(contents.get(i)), XContentType.JSON)

                );
           // }
        }
        BulkResponse bulk = null;
        try {
            bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            return !bulk.hasFailures();
        } catch (Exception e) {
            throw new ActionRequestValidationException();
        }
    }


    //2、获取这些数据实现搜索功能
    public List<Map<String, Object>> searchPage(String keyword,Integer pageNo,Integer pageSize) throws Exception {




        ArrayList<Map<String, Object>> maps = new ArrayList<>();

        if (pageNo <= 1) {
            pageNo = 1;
        }




        // 条件搜素
        SearchRequest searchRequest = new SearchRequest("jd-goods");




        // 构造builder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();


        // 分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);


        // 模糊匹配
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("title", keyword);
        // 模糊匹配放入builder中
        sourceBuilder.query(matchQuery);
        // 设置超时
        sourceBuilder.timeout(TimeValue.timeValueSeconds(3L));
        // 高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);


        // 把builder放入请求中
        searchRequest.source(sourceBuilder);
        // 执行查询
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : searchResponse.getHits()) {

            // 解析高亮字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();

            // 解析高亮字段，将原来的字段替换成我们高亮的字段即可
            if (null != title) {
                Text[] fragments = title.fragments();
                String n_title = "";
                for (Text text : fragments) {
                    n_title += text;
                }
                sourceAsMap.put("title", n_title); //替换高亮字段
            }


            maps.add(sourceAsMap);
        }
        return maps;
    }

    public Integer searchTotalCount(String keyword) throws IOException {

        // 条件搜素
        SearchRequest searchRequest = new SearchRequest("jd-goods");
        // 构造builder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 模糊匹配
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("title", keyword);
        // 模糊匹配放入builder中
        sourceBuilder.query(matchQuery);
        // 设置超时
        sourceBuilder.timeout(TimeValue.timeValueSeconds(3L));
        // 得到真实总数
        sourceBuilder.trackTotalHits(true);



        // 把builder放入请求中
        searchRequest.source(sourceBuilder);
        // 执行查询
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        TotalHits totalHits = searchResponse.getHits().getTotalHits();
        return (int)totalHits.value;
    }



    public boolean iSExistData(String index ,String title) throws IOException {
        SearchRequest searchRequest = new SearchRequest(index);
        //==
        //构造查询条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.filter(QueryBuilders.termQuery("title.keyword", title));
        sourceBuilder.query(boolQuery);
        sourceBuilder.timeout(TimeValue.timeValueSeconds(5L));
        // 把构建的条件搜索放入 查询请求中
        searchRequest.source(sourceBuilder);
        //==
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        int length = search.getHits().getHits().length;
        return length >= 1 ? true : false;
    }

}
